#include "main.h"

//LED
uchar led_code;

//SEG
uchar seg_pos;
uchar seg_str[12];
uchar seg_buf[8] = {0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF};
uchar seg_mode;

//KEY
uchar key_old;

//TIMER
ulong timer_count;

//SONIC
uchar sonic_val;


//===========LED=============
void led_proc() {
	if(timer_count%50) return;
	led_code = 0x01 << seg_mode;
	
}

//===========SEG=============
void seg_proc() {
	if(timer_count%50) return;
	
	switch(seg_mode) {
		case 0:
			sonic_val = sonic_read();
			sprintf(seg_str, "L      %d", (uint)sonic_val);
		break;
		case 1:
			sprintf(seg_str, "U      %d", (uint)2);
		break;
	}
	
	seg_tran(seg_str, seg_buf);
}

//===========KEY=============
void key_proc() {
	uchar key_val,key_down;
	if(timer_count%10) return;
	
	//读取键码
	key_val = key_scan_kbd();
	key_down = key_val & (key_old^key_val);
	key_old = key_val;
	
	//按键选择
	if(key_down == 4) {
		seg_mode = (++seg_mode)%2;
	}
	
	//双按键
	if(key_down == 89) {
		seg_mode = (++seg_mode)%2;
	}

}

//===========ISR=============
void timer1_init() {
	AUXR &= 0xBF;
	TMOD &= 0x0F;
	TH1 = 0xFC;  //1ms
	TL1 = 0x18;
	TF1 = 0;
	ET1 = 1;
	TR1 = 1;
	EA = 1;
}

void isr_timer_1() interrupt 3 {
	timer_count++;
	
	led_disp(led_code);
	seg_disp(seg_pos, seg_buf);
	if(++seg_pos == 8) seg_pos = 0;
}

//===========MAIN=============
void main() {
	sys_init();
	timer1_init();
	
	while(1) {
		led_proc();
		seg_proc();
		key_proc();
	}
}


